package com.xbk.seckill.reservation.application.event;

import com.alibaba.cola.dto.Response;
import com.alibaba.cola.event.EventHandler;
import com.alibaba.cola.event.EventHandlerI;
import com.alibaba.fastjson.JSON;
import com.xbk.seckill.common.model.enums.SeckillReservationUserStatus;
import com.xbk.seckill.reservation.application.cache.SeckillReservationConfigCacheService;
import com.xbk.seckill.reservation.application.cache.SeckillReservationUserCacheService;
import com.xbk.seckill.reservation.domain.event.SeckillReservationUserEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;

/**
 * 商品事件处理器
 *
 * @author xiexu
 * @date 2025/5/2 21:39
 */
@Slf4j
@EventHandler
@ConditionalOnProperty(name = "message.mq.type", havingValue = "cola")
public class SeckillReservationUserColaEventHandler implements EventHandlerI<Response, SeckillReservationUserEvent> {

    @Autowired
    private SeckillReservationUserCacheService seckillReservationUserCacheService;

    @Autowired
    private SeckillReservationConfigCacheService seckillReservationConfigCacheService;

    @Override
    public Response execute(SeckillReservationUserEvent seckillReservationUserEvent) {
        if (seckillReservationUserEvent == null || seckillReservationUserEvent.getId() == null || seckillReservationUserEvent.getGoodsId() == null) {
            log.info("cola|reservationUserEvent|接收秒杀品预约事件参数错误");
            return Response.buildSuccess();
        }
        log.info("cola|reservationUserEvent|接收秒杀品预约事件|{}", JSON.toJSON(seckillReservationUserEvent));

        if (seckillReservationUserEvent.getStatus() != null && SeckillReservationUserStatus.isDeleted(seckillReservationUserEvent.getStatus())) {
            log.info("cola|reservationUserEvent|删除缓存中的数据|{}", JSON.toJSONString(seckillReservationUserEvent));
            seckillReservationUserCacheService.deleteSeckillReservationUserFromCache(seckillReservationUserEvent);
        } else {
            log.info("cola|reservationUserEvent|更新缓存中的数据|{}", JSON.toJSONString(seckillReservationUserEvent));
            seckillReservationUserCacheService.tryUpdateSeckillReservationUserCacheByUserIdAndGoodsId(seckillReservationUserEvent.getId(), seckillReservationUserEvent.getGoodsId(), false);
            seckillReservationUserCacheService.tryUpdateGoodsListCacheByUserId(seckillReservationUserEvent.getId(), false);
            seckillReservationUserCacheService.tryUpdatetUserListCacheByGoodsId(seckillReservationUserEvent.getGoodsId(), false);
        }
        seckillReservationConfigCacheService.updateSeckillReservationConfigCurrentUserCount(seckillReservationUserEvent.getGoodsId(), seckillReservationUserEvent.getStatus(), 0L);
        return Response.buildSuccess();
    }

}
